package com.hzh;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

class MyMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        //先将Text类型转成Java中的String类型
        String line = value.toString();
        //每一行数据用空格分隔
        String[] strings = line.split(" ");
        for (String word : strings) {
            context.write(new Text(word), new LongWritable(1L));
        }
    }
}

class MyReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        Long sum = 0L;
        for (LongWritable value : values) {
            long l = value.get();
            sum += l;
        }
        context.write(key, new LongWritable(sum));
    }
}

/*
    编写mapreduce实现wordcount单词统计
 */
public class WordCountDemo {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        //获取Hadoop集群的环境配置
        Configuration conf = new Configuration();
        //创建一个任务
        Job job = Job.getInstance(conf);
        //设置reduce的数量
        job.setNumReduceTasks(1);
        job.setJobName("bigdata17testMapreduce");
        job.setJarByClass(WordCountDemo.class);
        //设置map类
        job.setMapperClass(MyMapper.class);
        //设置reduce类
        job.setReducerClass(MyReducer.class);
        //设置map任务出来的结果类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputKeyClass(LongWritable.class);

        //设置reduce输出结果的key和value的类型
        job.setMapOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        //指定数据在HDFS上的路径，这个路径将来需要自己手动传入
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        job.waitForCompletion(true);

    }
}
